package com.buyingtickets.service.impl;

import com.buyingtickets.dao.*;
import com.buyingtickets.entity.*;
import com.buyingtickets.service.StopoverStationService;
import com.buyingtickets.service.TrainNumberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author bwj
 * @date 2021/6/24 9:09
 */
@Service
public class TrainNumberServiceImpl implements TrainNumberService {
    @Resource
    private TrainNumberDao trainNumberDao;
    @Resource
    private InitialSeatDao initialSeatDao;
    @Resource
    private SeatDao seatDao;
    @Resource
    private StopoverStationDao stopoverStationDao;
    @Resource
    private UnitSeatDao unitSeatDao;
    @Resource
    private SiteDao siteDao;
    @Resource
    private CarriageDao carriageDao;
    @Resource
    private OrderDao orderDao;
    @Resource
    private TicketDao ticketDao;
    @Resource
    private StopoverStationService stopoverStationService;

    @Override
    //查询车次
    public List<TrainNumber> queryBySiteDao(String startName, String destinationName, String date) {
        //1、通过起点站点名、终点站点名分别查询站点ID
        int startId = siteDao.queryByName(startName);
        int destinationId = siteDao.queryByName(destinationName);
        //2、通过起点、终点站点ID和出发日期：查询车次ID、列车ID、列车类型、列车名字
        QueryParameter queryParameter = new QueryParameter();
        queryParameter.setStartId(startId);
        queryParameter.setDestinationId(destinationId);
        queryParameter.setDepartureDate(date);
        List<TrainNumber> trainNumberList2 = trainNumberDao.queryByDateSiteId(queryParameter);
        //2.1、通过列车ID、出发日期：查询车次ID、列车类型、列车名字(TrainNumberDao)(queryByDateSiteIdTwo)
        List<TrainNumber> trainNumberList = new ArrayList<TrainNumber>();
        TrainNumber trainNumber = new TrainNumber();
        for (TrainNumber t : trainNumberList2) {
            t.setDepartureDate(date);
            trainNumber = trainNumberDao.queryByDateSiteIdTwo(t);
            trainNumber.setStartId(startId);
            trainNumber.setDestinationId(destinationId);
            trainNumberList.add(trainNumber);
        }
        //3、通过列车ID、站点ID查询列车到站时间和站点顺序
        StopoverStation stopoverStation = new StopoverStation();
        Train train = new Train();
        Site site = new Site();
        site.setSiteId(startId);
        stopoverStation.setSite(site);
        int trainId;
        for (TrainNumber t : trainNumberList) {
            trainId = t.getTrain().getTrainId();
            train.setTrainId(trainId);
            stopoverStation.setTrain(train);
            stopoverStation.setArrivalTime(stopoverStationDao.queryByTrainSiteId(stopoverStation).getArrivalTime());
            t.setStartTime(stopoverStation.getArrivalTime());
            stopoverStation.setSiteOrder(stopoverStationDao.queryByTrainSiteId(stopoverStation).getSiteOrder());
            t.setStartOrder(stopoverStation.getSiteOrder());
        }
        site.setSiteId(destinationId);
        for (TrainNumber t : trainNumberList) {
            trainId = t.getTrain().getTrainId();
            train.setTrainId(trainId);
            stopoverStation.setTrain(train);
            stopoverStation.setArrivalTime(stopoverStationDao.queryByTrainSiteId(stopoverStation).getArrivalTime());
            t.setDestinationTime(stopoverStation.getArrivalTime());
            stopoverStation.setSiteOrder(stopoverStationDao.queryByTrainSiteId(stopoverStation).getSiteOrder());
            t.setDestinationOrder(stopoverStation.getSiteOrder());
        }
        //5、通过车次ID、起点站点顺序、终点站点顺序、座位类型、座位位置查询余票信息
        int price = 0;
        for (TrainNumber t : trainNumberList) {
            price = stopoverStationService.queryByTrainId(t);
            t.setPrice(price);
            List<UnitSeat> unitSeatList = unitSeatDao.queryByOrder(t);
            if (null == unitSeatList || unitSeatList.size() == 0) {
                t.setYesNo("无");
            } else {
                t.setYesNo("有");
            }
        }
        return trainNumberList;
    }

    @Override
    //换乘
    public List<TrainNumber> queryByHuanCheng(String startName, String destinationName, String date) {
        //1、通过起点站点名、终点站点名分别查询站点ID
        int startId = siteDao.queryByName(startName);
        int destinationId = siteDao.queryByName(destinationName);
        //2、通过起点、终点站点ID和出发日期：列车ID
        //2、通过起点、终点站点ID和出发日期：列车ID
        QueryParameter queryParameter = new QueryParameter();
        queryParameter.setStartId(startId);
        queryParameter.setDestinationId(destinationId);
        queryParameter.setDepartureDate(date);
        List<TrainNumber> trainNumberListTwo = trainNumberDao.queryByDateSiteId(queryParameter);
        //2.1、通过列车ID、出发日期：查询车次ID、列车类型、列车名字(TrainNumberDao)(queryByDateSiteIdTwo)
        List<TrainNumber> trainNumberList = new ArrayList<TrainNumber>();
        TrainNumber trainNumber = new TrainNumber();
        for (TrainNumber t : trainNumberListTwo) {
            t.setDepartureDate(date);
            trainNumber = trainNumberDao.queryByDateSiteIdTwo(t);
            trainNumber.setStartId(startId);
            trainNumber.setDestinationId(destinationId);
            trainNumberList.add(trainNumber);
        }
        //3、通过列车ID、站点ID查询列车到站时间和站点顺序
        StopoverStation stopoverStation = new StopoverStation();
        Train train = new Train();
        Site site = new Site();
        site.setSiteId(startId);
        stopoverStation.setSite(site);
        int trainId;
        for (TrainNumber t : trainNumberList) {
            trainId = t.getTrain().getTrainId();
            train.setTrainId(trainId);
            stopoverStation.setTrain(train);
            stopoverStation.setArrivalTime(stopoverStationDao.queryByTrainSiteId(stopoverStation).getArrivalTime());
            t.setStartTime(stopoverStation.getArrivalTime());
            stopoverStation.setSiteOrder(stopoverStationDao.queryByTrainSiteId(stopoverStation).getSiteOrder());
            t.setStartOrder(stopoverStation.getSiteOrder());
        }
        site.setSiteId(destinationId);
        for (TrainNumber t : trainNumberList) {
            trainId = t.getTrain().getTrainId();
            train.setTrainId(trainId);
            stopoverStation.setTrain(train);
            stopoverStation.setArrivalTime(stopoverStationDao.queryByTrainSiteId(stopoverStation).getArrivalTime());
            t.setDestinationTime(stopoverStation.getArrivalTime());
            stopoverStation.setSiteOrder(stopoverStationDao.queryByTrainSiteId(stopoverStation).getSiteOrder());
            t.setDestinationOrder(stopoverStation.getSiteOrder());
        }
        //5、通过车次ID、起点站点顺序、终点站点顺序、座位类型、座位位置查询余票信息
        StopoverStation stopoverStation2 = new StopoverStation();
        StopoverStation stopoverStation3 = new StopoverStation();
        Site site3 = new Site();
        List<TrainNumber> trainNumberListTwo2 = new ArrayList<>();
        QueryParameter queryParameter2 = new QueryParameter();
        Train train2 = new Train();
        Site site2 = new Site();
        int trainId2;
        List<TrainNumber> list = new ArrayList<TrainNumber>();
        int price = 0;
        int TwoStar;//列车2的始发站ID
        for (TrainNumber t : trainNumberList) {//循环车次1
            for (int i = t.getDestinationOrder(); i > t.getStartOrder(); i--) {
                t.setDestinationOrder(i);
                List<UnitSeat> unitSeatList = unitSeatDao.queryByOrder(t);
                if (null == unitSeatList || unitSeatList.size() == 0) {//若为空值，则无车票，终点顺序-1
                } else {//有车票，遍历车次2
                    //1、通过列车ID、站点顺序查询车次二的起点ID
                    stopoverStation2.setTrain(t.getTrain());
                    stopoverStation2.setSiteOrder(i);
                    TwoStar = stopoverStationDao.queryByOrder(stopoverStation2);
                    //2、通过起点、终点站点ID和出发日期：列车ID
                    queryParameter2.setStartId(TwoStar);
                    queryParameter2.setDestinationId(destinationId);
                    queryParameter2.setDepartureDate(date);
                    trainNumberListTwo2 = trainNumberDao.queryByDateSiteId(queryParameter2);

                    //2.1、通过列车ID、出发日期：查询车次ID、列车类型、列车名字
                    List<TrainNumber> trainNumberList2 = new ArrayList<TrainNumber>();
                    TrainNumber trainNumber2 = new TrainNumber();
                    for (TrainNumber t2 : trainNumberListTwo2) {
                        t2.setDepartureDate(date);
                        trainNumber2 = trainNumberDao.queryByDateSiteIdTwo(t2);
                        trainNumber2.setStartId(TwoStar);
                        trainNumber2.setDestinationId(destinationId);
                        trainNumberList2.add(trainNumber2);
                    }
                    //3、通过列车ID、站点ID查询列车到站时间和站点顺序
                    site2.setSiteId(TwoStar);
                    stopoverStation2.setSite(site2);
                    for (TrainNumber t2 : trainNumberList2) {
                        System.out.println(t2);
                        trainId2 = t2.getTrain().getTrainId();
                        train2.setTrainId(trainId2);
                        stopoverStation2.setTrain(train2);
                        stopoverStation2.setArrivalTime(stopoverStationDao.queryByTrainSiteId(stopoverStation2).getArrivalTime());
                        t2.setStartTime(stopoverStation2.getArrivalTime());
                        stopoverStation2.setSiteOrder(stopoverStationDao.queryByTrainSiteId(stopoverStation2).getSiteOrder());
                        t2.setStartOrder(stopoverStation2.getSiteOrder());
                    }
                    site2.setSiteId(destinationId);
                    for (TrainNumber t2 : trainNumberList2) {
                        trainId2 = t2.getTrain().getTrainId();
                        train2.setTrainId(trainId2);
                        stopoverStation2.setTrain(train2);
                        stopoverStation2.setArrivalTime(stopoverStationDao.queryByTrainSiteId(stopoverStation2).getArrivalTime());
                        t2.setDestinationTime(stopoverStation2.getArrivalTime());
                        stopoverStation2.setSiteOrder(stopoverStationDao.queryByTrainSiteId(stopoverStation2).getSiteOrder());
                        t2.setDestinationOrder(stopoverStation2.getSiteOrder());
                    }
                    //5、遍历车次2，
                    for (TrainNumber t2 : trainNumberList2) {
                        int z = t2.getDestinationTime().compareTo(t.getDestinationTime());
                        if (z == -1) {//车次2发车时间应不小于车次1（可以同车换乘）

                        } else {
                            List<UnitSeat> unitSeatList2 = unitSeatDao.queryByOrder(t2);
                            if (null == unitSeatList2 || unitSeatList2.size() == 0) {//若为空值，则无车票，继续遍历
                            } else {//若有值，则满足换乘条件，用集合接t和t2
                                //终点站ID///终点站到达时间//终点站序号
                                trainId = t.getTrain().getTrainId();
                                train.setTrainId(trainId);
                                stopoverStation3.setTrain(train);
                                stopoverStation3.setSiteOrder(i);//t的终点站序号
                                t.setDestinationId(stopoverStationDao.queryByOrder(stopoverStation3));//修改终点站ID
                                t.setDestinationOrder(i);//修改终点站序号
                                site3.setSiteId(stopoverStationDao.queryByOrder(stopoverStation3));
                                stopoverStation3.setSite(site3);
                                t.setDestinationTime(stopoverStationDao.queryByTrainSiteId(stopoverStation3).getArrivalTime());
                                t.setMiddleName(siteDao.queryById(i));//添加中间站的名称
                                price = stopoverStationService.queryByTrainId(t);
                                t.setPrice(price);
                                price=stopoverStationService.queryByTrainId(t2);
                                t2.setPrice(price);
                                t.setYesNo("有");
                                t2.setYesNo("有");
                                list.add(t);
                                list.add(t2);
                                break;
                            }
                        }
                    }
                    break;
                }

            }

        }
        return list;
    }

    @Override
    //一人出票
    public Ticket queryIdChuPiao(TrainNumber trainNumber) {
        int seatId = unitSeatDao.queryByChuPiaoOne(trainNumber);
        if (seatId == 0) {
            seatId = unitSeatDao.queryByChuPiaoTwo(trainNumber);
        }
        trainNumber.setSeatId(seatId);
        unitSeatDao.update(trainNumber);
        orderDao.insertInto(trainNumber);
        trainNumber.setOrderId(orderDao.queryUserTrainId(trainNumber));
        ticketDao.insert(trainNumber);
        return ticketDao.queryByOrderId(trainNumber);
    }


    @Override
    @Transactional
    public boolean addTrainNum(int trainid, String date, String time) {
        boolean flag = true;
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            simpleDateFormat.parse(date);
            if (trainid > 0 && date.contains("-") && time.contains(":")) {
                flag = flag && trainNumberDao.addTrainNum(trainid, date, time);//添加车次
            }
            //查询原始座位
            List<InitialSeat> initialSeats = initialSeatDao.queryInitialSeat(trainid);
            //查询车次
            TrainNumber trainNumber = trainNumberDao.isTrainNumber(trainid, date, time);
            for (InitialSeat initialSeat : initialSeats) {
                //添加座位
                flag = flag && seatDao.addSeat(trainNumber.getTrainNumberId(), initialSeat.getInitialSeatId());

            }

            //trainid查询经停站id集合
            List<Integer> stopoverStations = stopoverStationDao.queryBytrainid(trainid);
            //查询车次对应座位
            List<Seat> seats = seatDao.queryByTno(trainNumber.getTrainNumberId());
            //添加单元座位
            for (Integer i : stopoverStations) {
                for (Seat seat : seats) {
                    flag = flag && unitSeatDao.addUnitSeat(seat.getSeatId(), i);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return flag;
    }


    @Override
    public TrainNumber isTrainNumber(int trainid, String date, String time) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            simpleDateFormat.parse(date);
            if (StringUtils.hasText(date) && StringUtils.hasText(time)) {
                if (trainid > 0 && time.contains(":")) ;
                return trainNumberDao.isTrainNumber(trainid, date, time);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    @Override
    public List<TrainNumber> queryPage(int page, String name) {
        page = page > 0 ? 5 * (page - 1) : 0;

        return trainNumberDao.queryPage(page, "%" + name + "%");
    }

    @Override
    /**
     * 查询总条数
     * @param name
     * @return
     */
    public int queryAllCount(String name) {

        return trainNumberDao.queryAllCount("%" + name + "%");
    }

}
